<?php

require_once "DatabaseManager.php";
require_once "data/UserInfo.php";



class UsersManager extends DatabaseManager {
	
	private function authenticateUser($email, $password, $userType) {
			if ($userType == UserType::TEACHER) {
				$email = strtolower($email);
				$queryString = "SELECT id, encrypted_password, email_address FROM teachers WHERE LOWER(email_address) = '$email'";
			    $queryResults = mysql_query($queryString);
		 		$numberOfRows = mysql_num_rows($queryResults);
		 		if ($numberOfRows > 0) {
					// We found the email. Let's check the password.
			 		$row = mysql_fetch_array($queryResults);
					$encrypted_password = $row['encrypted_password'];
					if ($encrypted_password == md5($password)) {
						// Password is valid. Create authorization or retrieve from DB if already exists
						$authorization = md5($email.$password);
						$queryString = "SELECT * FROM authorizations WHERE authorization = '$authorization'";
					    $queryResults = mysql_query($queryString);
		 		        $numberOfRows = mysql_num_rows($queryResults);
		 		        if ($numberOfRows < 1) {
							// Insert the authorization in the DB
							$queryString = "INSERT INTO authorizations(authorization, email_address, user_type) VALUES ('$authorization', '$email', $userType)";
							$success= mysql_query($queryString);
							if (!$success) {	
								$jsonResults[MESSAGE] = Strings::DATA_BASE_ERROR;
								$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_SERVER_ERROR); 
							}
						}
						$jsonResults = array();
						$jsonResults[JSON_Tags::TOKEN] = $authorization;
						$jsonResults[JSON_Tags::TEACHER_ID] = $row['id'];
						$this->response(json_encode($jsonResults),StatusCodes::STATUS_CODE_SUCCESS);			
					} else {
						// Wrong password	
							$jsonResults[MESSAGE] = Strings::EMAIL_AND_PASSWORD_NOT_RECOGNIZED;
							$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_BAD_REQUEST);
					}
			} else {
				// Email not found	
				$jsonResults[MESSAGE] = Strings::EMAIL_AND_PASSWORD_NOT_RECOGNIZED;
				$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_BAD_REQUEST);
			}
		}
		else if ($userType == UserType::SECRETARY) {
				// Secretary Code. It is not the purpose of my application in this stage
				$jsonResults[MESSAGE] = Strings::SECRETARY_SUPPORT;
				$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_BAD_REQUEST);
		}
		else {
			// Invalid user type
			$jsonResults[MESSAGE] = Strings::INVALID_USER_TYPE;
			$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_BAD_REQUEST);
		}
	}
	
	public function getUserInfoForAuthorization() {
		$headers =  apache_request_headers();
        if (isset($headers['Authorization'])) {
			$authorization = addslashes($headers['Authorization']);
			$queryString = "SELECT email_address, user_type FROM authorizations WHERE authorization = '$authorization'";  
			$queryResults = mysql_query($queryString);
		 	$numberOfRows = mysql_num_rows($queryResults);
		 		if ($numberOfRows > 0) {
					// We found the email. Let's check the password.
			 		$row = mysql_fetch_array($queryResults);
					$userType = $row['user_type'];
					if ($userType == UserType::TEACHER) {
						$email_address = $row['email_address'];
						// Get Teacher Id	
						$queryString = "SELECT id FROM teachers WHERE email_address = '$email_address'";  
						$queryResults = mysql_query($queryString);
		 				$numberOfRows = mysql_num_rows($queryResults);
		 				if ($numberOfRows > 0) {
							// Teacher _Id
			 				$row = mysql_fetch_array($queryResults);
							$userInfo = new UserInfo();
							$userInfo->userType = $userType;
							$userInfo->userId = $row['id'];
							return $userInfo;
						}
					} else if ($userType == UserType::SECRETARY) {
							// Secretary Code. It is not the purpose of my application in this stage
							$jsonResults[MESSAGE] = Strings::SECRETARY_SUPPORT;
							$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_BAD_REQUEST);
					} else {
						// Regular user (Ex. Student)
						$userInfo = new UserInfo();
						$userInfo->userType = $userType;
						return $userInfo;	
					}
				} else {
					// Invalid token
					$jsonResults[MESSAGE] = Strings::INVALID_TOKEN;
					$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_FORBIDDEN);	
				}
		}
		else {
			// Authorization is missing	
			$jsonResults[MESSAGE] = Strings::AUTH_TOKEN_MISSING;
			$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_FORBIDDEN);	
		}
	}
	
	public function processApi(){
		// Check permissions
		$this->getUserInfoForAuthorization();
        $this->_request = file_get_contents("php://input");
		$METHOD = $this->get_request_method();
		if ($METHOD == "POST") {
				parse_str($_SERVER['QUERY_STRING'], $queryStringParsed);
				if (isset($queryStringParsed['action'])) {
					if ($queryStringParsed['action'] == 'signin') {
						$postContent = json_decode($this->_request, true);
						if ($postContent) {
							if (isset($postContent[JSON_Tags::USER_EMAIL])) {
								$email = addslashes($postContent[JSON_Tags::USER_EMAIL]);	
							} else {
								// Email not set	
								$jsonResults[MESSAGE] = Strings::EMAIL_NOT_SET;
								$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_BAD_REQUEST);
							}
							if (isset($postContent[JSON_Tags::USER_PASSWORD])) {
								$password = addslashes($postContent[JSON_Tags::USER_PASSWORD]);	
							} else {
								// Password not set
								$jsonResults[MESSAGE] = Strings::PASSWORD_NOT_SET;
								$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_BAD_REQUEST);	
							}
							if (isset($postContent[JSON_Tags::USER_TYPE])) {
								$userType = addslashes($postContent[JSON_Tags::USER_TYPE]);
							} else {
								// User type not set	
								$jsonResults[MESSAGE] = Strings::USER_TYPE_NOT_SET;
								$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_BAD_REQUEST);
							}
							if (count($postContent) != 3) {
								// If any extra elements, invalidate the JSON	
								$jsonResults[MESSAGE] = Strings::BAD_REQUEST;
								$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_BAD_REQUEST);
							}
							$this->authenticateUser($email, $password, $userType);
						} else {
							$jsonResults[MESSAGE] = Strings::BAD_REQUEST;
							$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_BAD_REQUEST); 
						}
					}
				     else {
						$jsonResults[MESSAGE] = Strings::BAD_REQUEST;
						$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_BAD_REQUEST);  
					 }
				} else {
					// Bad JSON
					$jsonResults[MESSAGE] = Strings::BAD_REQUEST;
					$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_BAD_REQUEST); 	
				}
		} else {
			// Not supported method	
			$jsonResults[MESSAGE] = Strings::HTTP_METHOD_NOT_SUPPORTED;
			$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_BAD_REQUEST);
		}
	}
}	
?>